<?php
namespace app\index\controller;

use app\common\model\index\UserModel;
use think\admin\extend\CodeExtend;
use think\admin\service\CaptchaService;
use think\facade\Validate;

/**
 * 登录
 * @package app\index\controller
 * @author wangqinghui
 * @DateTime 2024-09-03 11:28:47
 */
class Login extends BaseIndex
{

    public function index()
    {
        $this->title = lang('登录注册');
        if(!$this->request->isPost()){
            // 登录验证令牌
            $this->captchaType = 'indexLoginCaptcha';
            $this->captchaToken = CodeExtend::uuid();
            $this->fetch('index');
        }else{
            $params = $this->request->post();
            $rule = [
                'account|用户名' => 'require',
                'password|密码'  => 'require',
                'verify|图形验证码'   => 'require',
                'uniqid|图形验证标识'   => 'require',
            ];
            $valid = Validate::rule($rule);
            if(!$valid->check($params)){
                $this->error($valid->getError());
            }
            if (!CaptchaService::instance()->check($params['verify'], $params['uniqid'])) {
                $this->error('图形验证码验证失败，请重新输入!');
            }
            // 验证用户名是否唯一
            $map = [
                ['account', '=', $params['account']],
                ['is_deleted', '=', 0]
            ];
            $user_info = UserModel::mk()->where($map)->find();
            if(empty($user_info['id'])){
                $this->error('该用户暂未注册');
            }
            if (md5("{$user_info['password']}{$params['uniqid']}") !== $params['password']) {
                $this->error('密码错误');
            }
            $user_info->hidden(['password', 'is_deleted', 'password_plaintext']);
            $this->app->session->set('index_user', $user_info->toArray());
            $this->success('登录成功', sysuri('index/index'));
        }
    }

    /**
     * 注册
     * @author wangqinghui
     * @DateTime 2024-09-03 16:56:03
     * @return void
     */
    public function register()
    {
        $params = $this->request->post();
        $rule = [
            'account|用户名' =>'require|alphaNum|length:4,20',
            'mobile|手机号'   =>'require|mobile|length:11',
            // 密码包含字母或数字或符号
            'password|密码'  => ['require', 'length' => '6,20', 'regex' => '/^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?!([^(0-9a-zA-Z)]|[\(\)])+$)([^(0-9a-zA-Z)]|[\(\)]|[a-z]|[A-Z]|[0-9]){6,}$/'],
            'check_password|确认密码'  =>'require|confirm:password'
        ];
        $valid = Validate::rule($rule);
        if(!$valid->check($params)){
            $this->error($valid->getError());
        }
        // 验证用户名是否唯一
        $map = [
            ['account', '=', $params['account']],
            ['is_deleted', '=', 0]
        ];
        $findInfo = UserModel::mk()->where($map)->field('id')->find();
        if(!empty($findInfo['id'])){
            $this->error('用户名已注册');
        }
        // 验证手机号是否唯一
        $map = [
            ['mobile', '=', $params['mobile']],
            ['is_deleted', '=', 0]
        ];
        $findInfo = UserModel::mk()->where($map)->field('id')->find();
        if(!empty($findInfo['id'])){
            $this->error('该手机号已被占用');
        }
        $default_avatar = '/static/plugs/index/img/default_avatar.png';
        $userData = [
            'account'   =>  $params['account'],
            'password'  =>  md5($params['password']),
            'password_plaintext'    =>  $params['password'],
            'mobile'    =>  $params['mobile'],
            'avatar'    =>  $default_avatar,
        ];
        $user_id = UserModel::mk()->insertGetId($userData);
        if($user_id <= 0){
            $this->error('注册失败');
        }
        // 获取用户信息
        $user_info = UserModel::mk()->where(['id' => $user_id])->find();
        if(empty($user_info['id'])){
            $this->error('用户信息有误');
        }
        $user_info->hidden(['password', 'is_deleted', 'password_plaintext', 'mobile', 'create_at', 'update_at']);
        $this->app->session->set('index_user', $user_info->toArray());
        sysoplog('用户注册', '用户注册成功'.json_encode($user_info->toArray()));
        $this->success('注册成功', sysuri('login/index'));
    }

    /**
     * 获取验证码
     * @author wangqinghui
     * @DateTime 2024-09-04 18:16:55
     * @return void
     */
    public function captcha()
    {
        $input = $this->_vali([
            'type.require'  => lang('类型不能为空'),
            'token.require' => lang('标识不能为空'),
        ]);
        $image = CaptchaService::instance()->initialize();
        $captcha = ['image' => $image->getData(), 'uniqid' => $image->getUniqid()];
        if ($this->app->session->get($input['type']) === $input['token']) {
            $captcha['code'] = $image->getCode();
            $this->app->session->delete($input['type']);
        }
        $this->success('生成验证码成功', $captcha);
    }


    /**
     * 退出登录
     * @author wangqinghui
     * @DateTime 2024-09-04 18:16:38
     * @return void
     */
    public function out()
    {
        $this->app->session->delete('index_user');
        $this->success('退出登录成功!');
    }
}